// miniprogram/pages/publish/publish.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    concats: [{
      name: 'qq',
      value: 'qq',
      checked: 'true'
    }, {
      name: '微信',
      value: 'wechat'
    }],
    tags: [],
    rawDate: '',
    showDate: {},
    tmpImgs: [],
    person: null,
    keywords: "",
    focus: false,
    info: {
      tag: '',
      date: '',
      desc: '',
      place: '',
      imgs: [],
      concat: {}, // 联系方式
      type: '',
      anonymity: false,
      keywords: [],
      is_delete: false,
      status: "progress"
    }
  },
  async save() {
    if (!this.data.info.place) {
      return wx.showToast({
        title: '请输入地点',
        icon: 'none'
      })
    }
    if (!this.data.info.concat) {
      return wx.showToast({
        title: '至少选择一种联系方式',
        icon: 'none'
      })
    }
    if (this.data.tmpImgs.length > 0){
      wx.showLoading({
        title: '正在上传图片',
      })
      let list = []
      for (let i = 0, len = this.data.tmpImgs.length; i < len; i++) {
        let item = this.data.tmpImgs[i]
        const filenameArr = item.split('/')
        const filename = filenameArr[filenameArr.length - 1]
        let res = null
        let mouth = (new Date()).getMonth()+1
        try {
          res = await wx.cloud.uploadFile({
            cloudPath: 'lostAndFound/uploads/' + (new Date()).getFullYear() + '/' + mouth + '/' + (new Date()).getDate() + '/' + filename,
            filePath: item, // 文件路径
          })
        } catch (err) {
          wx.hideLoading()
          wx.showToast({
            title: '图片上传失败',
            icon: 'none'
          })
          console.log(err)
          return
        }
        list.push(res.fileID)
      }
      this.setData({
        'info.imgs': list
      })
      wx.hideLoading()
    }

    wx.showLoading({
      title: '正在保存...',
    })
    if (this.data.info.desc){
      //let reg = /\(([^)]*)\)/;
      ///(?:#)\w+(?:#)/g
      ///#([^##]+)#/g
      //while(r=reg.exec(str)){console.log(r[1])}
      await wx.cloud.callFunction({
        name: "util",
        data: {
          $url: 'getKeywords',
          desc: this.data.info.desc
        }
      }).then(res => {
        if(res.result.code === 200){
          let lis = []
          for (let item of res.result.data.items){
            if(item.pos ==='m' || item.pos.indexOf('n') !==-1 || item.ne ==='PER'){
              lis.push(item.item)
            }
          }
          lis.push(this.data.info.tag)
          lis.push(this.data.info.place)
          this.data.info.keywords = lis
        }
      })
    }
    this.data.info.publishDate = new Date()
    const db = wx.cloud.database()
    const res = await db.collection('list').add({
      data: this.data.info
    })
    wx.hideLoading()
    if (res) {
      console.log(res)
      wx.showToast({
        title: '保存成功',
      })
      wx.navigateBack({
        delta: 2,
      })
    } else {
      return wx.showToast({
        title: '保存失败...',
        icon: 'none'
      })
    }
  },

  /**
   * 匿名
   */
  switchChange: function (e) {
    this.setData({
      'info.anonymity': e.detail.value
    })
  },
  /**
   * 联系方式
   */
  checkboxChange: function (e) {
    const value = e.detail.value
    const concat = {}
    if (value.indexOf('wechat') !== -1) {
      concat.wechat = this.data.person.wechat
    }
    if (value.indexOf('qq') !== -1) {
      concat.qq = this.data.person.qq
    }
    this.setData({
      'info.concat': concat
    })
  },

  /**
   * 动态输入框
   */
  handelInput(e) {
    const id = e.currentTarget.id
    const value = e.detail.value
    const obj = {}
    obj['info.' + id] = value
    this.setData(obj)
  },

  /**
   * 绑定标签改变
   */
  bindTagChange(e) {
    let tags = this.data.tags;
    let index = e.detail.value;
    this.setData({
      'info.tag': tags[index]
    })
  },

  /**
   * 删除照片
   */
  delPic(e) {
    const index = e.currentTarget.dataset.index
    const list = [...this.data.tmpImgs]
    list.splice(index, 1)
    this.setData({
      tmpImgs: list
    })
  },

  /**
   * 选择照片
   */
  selcetPics() {
    console.log(3 - this.data.tmpImgs.length);

    if (this.data.tmpImgs.length < 3) {
      wx.chooseImage({
        count: 3 - this.data.tmpImgs.length,
        success: (res) => {
          console.log(res)
          if (res.tempFilePaths.length > 0) {
            this.setData({
              tmpImgs: [...this.data.tmpImgs, ...res.tempFilePaths]
            })
          }
        },
      })
    } else {
      wx.showToast({
        title: '最多上次三张',
        icon: 'none'
      })
    }
  },

  /**
   * 绑定更换时间
   */
  bindDateChoose(e) {
    const kws = this.data.keywords
    const date = `${this.data.showDate.y}/${this.data.showDate.m}/${this.data.showDate.d}`
    wx.navigateTo({
      url: '/pages/date/select?kws=' + kws + '&date=' + date
    })
  },

  /**
   * 设置日期
   */
  _setDate(rawDate) {
    // rawDate 是任意可以转换为Date对象的数据
    const date = new Date(rawDate)
    date.setHours(0)
    date.setMinutes(0)
    const showDate = {
      y: this._toTwo(date.getFullYear()),
      m: this._toTwo(date.getMonth() + 1),
      d: this._toTwo(date.getDate())
    }
    this.setData({
      showDate,
      rawDate,
      'info.date': date
    })
  },

  /**
   * 格式化时间
   */
  _toTwo(value) {
    return (value + '').length < 2 ? '0' + value : value + ''
  },

  /**
   * 初始化标签
   */
  _loadTags: function () {
    let _this = this
    wx.cloud.callFunction({
      name: "tags",
      data: {
        $url: 'getTags'
      }
    }).then(res => {
      if(res.result.code === 200){
        let tags = res.result.data[0].lists.map((item) => {return item.value})
        _this.setData({
          tags,
          'info.tag': tags[0]
        })
      }
    })
  },

  /**
   * 加载个人信息
   */
  async _loadPersonalInfo() {
    const db = wx.cloud.database();
    let user;
    try {
      user = await db.collection('users').get()
    } catch (err) {
      wx.showToast({
        title: '加载个人信息失败，请重启小程序',
        icon: 'none',
        duration: 3000,
        mask: true,
        success: function () {
          setTimeout(function() {
            wx.navigateBack()
          }, 2000);
        }
      })
    }

    console.log(user)
    if (user.data.length > 0) {
      const userInfo = user.data[0]
      if (!userInfo.qq || !userInfo.wechat) {
        wx.showToast({
          title: '还没有完善个人信息，请先完善个人信息',
          icon: 'none',
          duration: 3000,
          mask: true,
          success: function () {
            setTimeout(function() {
              wx.redirectTo({
                url: '/pages/profile/profile',
              })
            }, 2000)
          }
        })
      }
      this.setData({
        person: userInfo,
        'info.concat': {
          qq: userInfo.qq
        }
      })
    } else {
      wx.showToast({
        title: '授权后才可以使用发布功能哦~',
        mask: true,
        icon: 'none',
        success: function () {
          setTimeout(function() {
            wx.switchTab({
              url: '/pages/mine/mine',
            })
          }, 2000)
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    wx.setNavigationBarTitle({
      title: options.type === "lost" ? "寻物启事" : "失物招领" 
    })
    this._loadTags()
    this._loadPersonalInfo()

    this.setData({
      keywords: options.type === "lost" ? "丢失" : "拾取",
      'info.type': options.type
    })
    this._setDate((new Date).getTime())
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let _this = this;
    const query = wx.createSelectorQuery();
    query.select('#desc-view').boundingClientRect();
    query.exec(function (res) {  
      let dwidth = parseInt(res[0].width);
      _this.setData({
        textareaWidth: dwidth
      })
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})